package com.scnu.edu.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Data
@Component
@ConfigurationProperties(prefix = "alipay")
public class AliPayConfig {
    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.appPrivateKey}")
    private String appPrivateKey;  // 确保属性名与配置文件一致

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    public String getCHARSET() {
        return CHARSET;
    }

    // 支付宝网关（沙箱环境）
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "json";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @PostConstruct
    public void init() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipaydev.com";
        config.signType = "RSA2";
        config.appId = this.appId;
        config.merchantPrivateKey = this.appPrivateKey;
        config.alipayPublicKey = this.alipayPublicKey;
        config.notifyUrl = this.notifyUrl;
        Factory.setOptions(config);
//        打印私钥检查报错
        System.out.println("AppPrivateKey: " + (appPrivateKey == null ? "NULL" : "NOT NULL, length: " + appPrivateKey.length()));

    }

    /**
     * 发送支付请求到支付宝
     */
    public String sendRequestToAlipay(String orderNo, double amount, String subject) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL, appId, appPrivateKey, FORMAT, CHARSET, alipayPublicKey, SIGN_TYPE
        );

        com.alipay.api.request.AlipayTradePagePayRequest request = new com.alipay.api.request.AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);

        String bizContent = "{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"total_amount\":\"" + amount + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                "}";
        request.setBizContent(bizContent);

        // 关键：确保返回的是表单HTML
        return alipayClient.pageExecute(request).getBody();
    }
    /**
     * 查询订单状态（使用老版本SDK方式）
     */
    public String query(String outTradeNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                appId,
                appPrivateKey,
                FORMAT,
                CHARSET,
                alipayPublicKey,
                SIGN_TYPE
        );

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            return response.getBody();
        } else {
            return "查询失败，错误码：" + response.getCode() + "，错误信息：" + response.getMsg();
        }
    }

    @PostMapping("/notify")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request) {
        // 验证签名、更新订单状态...
        return "success"; // 必须返回纯文本 "success"
    }

}